package view;

import DAO.FileDAO;
import DAO.NewsDAO;
import DAO.UserDAO;
import crawler.NewsThread;
import tools.Encription;
import vo.News;
import vo.User;

import java.util.ArrayList;
import java.util.Scanner;


public class Main {
    //用户操作界面：以模块方式进行：
    public static void main(String[] args) throws Exception {
        User currentUser =  login();
        String role = currentUser.getRole();
        String userName = currentUser.getUserName();
        if(!"".equals(role)){//登陆成功
            //显示主界面，并选择
            int choice = mainMenu();
            while(choice != 3){//不选择退出
                switch (choice){
                    case 1://用户操作
                        user_drive(role,userName);
                        break;
                    case 2://新闻操作
                        news_drive(role);
                        break;
                    default:
                        System.out.println("指令无效，请重新输入！");
                        break;
                }
                choice = mainMenu();
            }
        }else{
            System.out.println("登录失败，程序退出");
        }
        System.out.println("感谢使用WTU计智学院新闻综合管理系统v1.0");
    }
    //返回用户身份role
    public static User login() {
        String role = "";
        int checkCount = 0;
        Scanner sc = new Scanner(System.in);
        while (checkCount < 3) {
            System.out.print("请输入用户名：");
            String userName = sc.nextLine();
            System.out.print("请输入密码：");
            String password = sc.nextLine();
            String encryptedPassword = null; // 加密输入的密码
            try {
                encryptedPassword = Encription.md5(password);
                User currentUser = UserDAO.get(userName);
                if (currentUser == null) {
                    System.out.println("用户不存在，请重新输入。");
                    checkCount++;
                } else {
                    //密码匹配
                    if (currentUser.getPassword().equals(encryptedPassword)) {
                        role = currentUser.getRole();
                        System.out.println("登录成功！用户身份为：" + currentUser.getRole());
                        return currentUser;
                    } else {
                        System.out.println("密码错误，请重新输入。");
                        checkCount++;
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        if ("".equals(role)) System.out.println("登录失败，已超过最大尝试次数。");
        return null;
        /*
        如果跟课上老师一样在此处关闭sc即sc.close()，则会影响到主菜单部分的输入
         */
    }
    //主菜单
    public static int mainMenu(){//用户菜单
        Scanner sc = new Scanner(System.in);
        int comm = 0;
        System.out.println("欢迎使用WTU计智学院新闻综合管理系统v1.0");
        System.out.println("1.用户操作");
        System.out.println("2.新闻操作");
        System.out.println("3.退出");
        System.out.print("请选择(1-3): ");
        comm = sc.nextInt();
        sc.nextLine(); // 消耗换行符
        return comm;
    }
    public static void user_drive(String role,String userName) throws Exception {
        Scanner sc = new Scanner(System.in);
        int choice = 0;
        if(role.equals("普通用户")){
            choice = subMenu1();
            while(choice != 2){
                switch (choice){
                    case 1://用户密码修改
                        System.out.println("请输入密码：");
                        String password = sc.nextLine();
                        UserDAO.update(userName,password);
                        break;
                    default:
                        System.out.println("指令无效，请重新输入！");
                        break;
                }
                choice = subMenu1();
            }
        }else{
            choice = subMenu2();
            while(choice != 5) {
                switch (choice) {
                    case 1://用户密码修改
                        System.out.println("请输入用户名：");
                        userName = sc.nextLine();
                        System.out.println("请输入密码：");
                        String password = sc.nextLine();
                        UserDAO.update(userName,password);
                        break;
                    case 2://用户删除
                        System.out.println("请输入用户名：");
                        userName = sc.nextLine();
                        System.out.println("请输入密码：");
                        password = sc.nextLine();
                        UserDAO.delete(userName,password);
                        break;
                    case 3://用户添加
                        System.out.println("请输入用户名：");
                        userName = sc.nextLine();
                        System.out.println("请输入密码：");
                        password = sc.nextLine();
                        System.out.println("请输入姓名：");
                        String name = sc.nextLine();
                        System.out.println("请输入用户身份（普通用户/管理员）：");
                        String new_role = sc.nextLine();
                        User new_user = new User(userName,password,name,new_role);
                        UserDAO.insert(new_user);
                        break;
                    case 4://用户查询
                        System.out.println("请输入用户名：");
                        userName = sc.nextLine();
                        System.out.println("请输入姓名（可回车跳过）：");
                        name = sc.nextLine();
                        System.out.println("请输入用户身份（普通用户/管理员）（可回车跳过）：");
                        role = sc.nextLine();
                        User user = new User(userName,"",name,role);
                        ArrayList<User> users = new ArrayList<>();
                        users = UserDAO.query(user);
                        show_userList(users);//打印符合查询条件的所有信息
                        break;
                    default:
                        System.out.println("指令无效，请重新输入！");
                        break;
                }
                choice = subMenu2();
            }
        }
    }
    //普通用户处理用户菜单
    public static int subMenu1(){
        int comm = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("1.用户密码修改");
        System.out.println("2.退出");
        System.out.print("请选择(1-2): ");
        comm = sc.nextInt();
        sc.nextLine(); // 消耗换行符
        return comm;
    }
    //管理员处理用户菜单
    public static int subMenu2(){
        int comm = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("1.用户密码修改");
        System.out.println("2.用户删除");
        System.out.println("3.用户添加");
        System.out.println("4.用户查询");
        System.out.println("5.退出");
        System.out.print("请选择(1-5): ");
        comm = sc.nextInt();
        sc.nextLine(); // 消耗换行符
        return comm;
    }
    public static void show_userList(ArrayList<User> users){
        System.out.println("用户名" + "|" + "密码" + "|" + "姓名" + "|" + "用户身份");
        for (User user : users) {
            System.out.println(user.toString());
        }
    }
    //**********************新闻处理**********************
    public static void news_drive(String role) throws Exception {
        Scanner sc = new Scanner(System.in);
        int choice = 0;
        if(role.equals("普通用户")){
            choice = subMenu3();
            while(choice != 3){
                switch (choice){
                    case 1://查询新闻
                        search_news();
                        break;
                    default:
                        System.out.println("指令无效，请重新输入！");
                        break;
                }
                choice = subMenu3();
            }
        }else{
            choice = subMenu4();
            while(choice != 7){
                switch (choice) {
                    case 1://新闻查询
                        search_news();
                        break;
                    case 2://新闻导入
                        inputNews();
                        break;
                    case 3://新闻导出
                        outputNews();
                        break;
                    case 4://新闻删除
                        System.out.println("请输入要删除的新闻的序号：");
                        int id = sc.nextInt();
                        sc.nextLine(); // 消耗换行符
                        if(NewsDAO.delete(id) == true){
                            System.out.println("删除成功！");
                        }else System.out.println("删除失败！");
                        break;
                    case 5://新闻修改
                        System.out.println("请输入要修改的新闻的序号：");
                        id = sc.nextInt();
                        sc.nextLine(); // 消耗换行符
                        System.out.println("请输入新的新闻标题：");
                        String new_title = sc.nextLine();
                        if(NewsDAO.update(id,new_title) == true){
                            System.out.println("修改成功！");
                        }else System.out.println("修改失败！");
                        break;
                    case 6://从官网新闻爬取100条新闻
                        String url = "https://csai.wtu.edu.cn/index/xyxw.htm"; // 要爬取的页面URL
                        NewsThread newsThread = new NewsThread(url);
                        Thread thread = new Thread(newsThread); // 创建一个线程来执行爬取逻辑
                        thread.start();//通过start()方法启动了线程，从而执行run()方法中的爬取逻辑
                        break;
                    default:
                        System.out.println("指令无效，请重新输入！");
                        break;
                }
                choice = subMenu4();
            }
        }
    }
    //普通用户处理新闻菜单
    public static int subMenu3(){
        int comm = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("1.查询新闻");
        System.out.println("2.退出");
        System.out.print("请选择(1-2): ");
        comm = sc.nextInt();
        sc.nextLine(); // 消耗换行符
        return comm;
    }
    //管理员处理新闻菜单
    public static int subMenu4(){
        int comm = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("1.查询新闻");
        System.out.println("2.新闻导入");
        System.out.println("3.新闻导出");
        System.out.println("4.新闻删除");
        System.out.println("5.新闻标题修改");
        System.out.println("6.从官网新闻爬取100条新闻");
        System.out.println("7.退出");
        System.out.print("请选择(1-7)： ");
        comm = sc.nextInt();
        sc.nextLine(); // 消耗换行符
        return comm;
    }
    //用户通用查询新闻
    public static void search_news() throws Exception {
        Scanner sc = new Scanner(System.in);
        int choice = serach_menu();
        while(choice != 5){
            switch (choice) {
                case 1://按序号查询
                    News news = new News();
                    System.out.println("请输入序号：");
                    int id = sc.nextInt();
                    sc.nextLine();// 消耗换行符
                    news = NewsDAO.getFromId(id);
                    show_news(news);//打印结果
                    break;
                case 2://按标题查询
                    System.out.println("请输入标题：");
                    String title = sc.nextLine();
                    news = NewsDAO.getFromTitle(title);
                    show_news(news);//打印结果
                    break;
                case 3://按作者查询
                    ArrayList<News> newsList = new ArrayList<>();
                    System.out.println("请输入作者：");
                    String author = sc.nextLine();
                    newsList = NewsDAO.getFromAuthor(author);
                    show_newsList(newsList);//打印结果
                    break;
                case 4://按多条件查询：标题（作者）
                    System.out.println("请输入标题：");
                    title = sc.nextLine();
                    System.out.println("请输入作者（可回车跳过）：");
                    author = sc.nextLine();
                    news = new News(0,title,"",author,"",0);
                    newsList = NewsDAO.query(news);
                    show_newsList(newsList);//打印结果
                    break;
                default:
                    System.out.println("指令无效，请重新输入！");
                    break;
            }
            choice = serach_menu();
        }
    }
    public static int serach_menu(){
        int comm = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("1.按序号查询");
        System.out.println("2.按标题查询");
        System.out.println("3.按作者查询");
        System.out.println("4.按多条件查询");
        System.out.println("5.退出");
        System.out.print("请选择(1-5): ");
        comm = sc.nextInt();
        sc.nextLine(); // 消耗换行符
        return comm;
    }
    public static void show_news(News news){
        System.out.println("序号|标题|链接地址|作者|发稿时间|浏览人数");
        System.out.println(news.toString());
    }
    public static void show_newsList(ArrayList<News> newses){
        System.out.println("序号|标题|链接地址|作者|发稿时间|浏览人数");
        for (News news : newses) {
            System.out.println(news.toString());
        }
    }
    //导入方式选择
    public static void inputNews(){
        Scanner sc = new Scanner(System.in);
        int choice = importMenu();
        while(choice != 3){//不是返回
            switch (choice){
                case 1://键盘导入
                    inputFromKeyboard();
                    break;
                case 2://文件导入
                    inputFromFile();
                    break;
                default:
                    System.out.println("指令无效，请重新输入！");
                    break;
            }
            choice = importMenu();
        }
    }
    //导入方式菜单
    public static int importMenu(){
        int comm = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("1.键盘导入");
        System.out.println("2.文件导入");
        System.out.println("3.退出");
        System.out.print("请选择(1-3): ");
        comm = sc.nextInt();
        sc.nextLine(); // 消耗换行符
        return comm;
    }
    //导出方式选择
    public static void outputNews() throws Exception {
        Scanner sc = new Scanner(System.in);
        int choice = outportMenu();
        while(choice != 3){//不是返回
            switch (choice){
                case 1://CSV文件导出
                    outputFromCSV();
                    break;
                case 2://XLS文件导出
                    outputFromXLS();
                    break;
                default:
                    System.out.println("指令无效，请重新输入！");
                    break;
            }
            choice = outportMenu();
        }
    }
    //导出方式菜单
    public static int outportMenu(){
        int comm = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("1.CSV文件导出");
        System.out.println("2.XLS文件导出");
        System.out.println("3.退出");
        System.out.print("请选择(1-3): ");
        comm = sc.nextInt();
        sc.nextLine(); // 消耗换行符
        return comm;
    }
    //CSV文件导出
    public static void outputFromCSV() throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入文件路径：");
        //C:\Users\ROG\Desktop\news_csv.csv
        String FilePath = sc.nextLine();
        FileDAO.WriteCSV(NewsDAO.printAll(),FilePath);
    }
    //XLS文件导出
    public static void outputFromXLS() throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入文件路径：");
        //C:\Users\ROG\Desktop\news_xls.xls
        String FilePath = sc.nextLine();
        FileDAO.WriteXLS(NewsDAO.printAll(),FilePath);
    }
    //键盘录入
    public static void inputFromKeyboard(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入编号：");
        int id = sc.nextInt();
        sc.nextLine();// 消耗换行符
        System.out.println("请输入标题：");
        String title = sc.nextLine();
        System.out.println("请输入链接地址：");
        String address = sc.nextLine();
        System.out.println("请输入作者：");
        String author = sc.nextLine();
        System.out.println("请输入发稿时间：");
        String fagaoshijian = sc.nextLine();
        System.out.println("请输入浏览人数：");
        int click = sc.nextInt();
        News news = new News(id + 400,title,address,author,fagaoshijian,click);//4开头为键盘读入
        try {
            NewsDAO.insert(news);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //CSV文件录入
    public static void inputFromCSV(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入文件路径：");
        String FilePath = sc.nextLine();
        ArrayList<News> newses = new ArrayList<>();
        newses = FileDAO.ReadCSV(FilePath);
        for(News news : newses){
            try {
                NewsDAO.insert(news);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    //XLS文件录入
    public static void inputFromXLS(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入文件路径：");

        String FilePath = sc.nextLine();
        ArrayList<News> newses = new ArrayList<>();
        newses = FileDAO.ReadXLS(FilePath);
        for(News news : newses){
            try {
                NewsDAO.insert(news);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    //Json录入
    //D:\\JAVAProject\\test\\Java_class\\src\\package.json
    public static void inputFromJSON(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入文件路径：");
        String FilePath = sc.nextLine();
        ArrayList<News> newses = new ArrayList<>();
        newses = FileDAO.ReadFromJson(FilePath);
        for(News news : newses){
            try {
                NewsDAO.insert(news);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    //文件导入
    public static void inputFromFile(){
        Scanner sc = new Scanner(System.in);
        int choice = subMenu();
        while(choice != 4){//不是返回
            switch (choice){
                case 1://CSV文件导入
                    inputFromCSV();
                    break;
                case 2://XLS文件导入
                    inputFromXLS();
                    break;
                case 3://JSON文件导入
                    inputFromJSON();
                    break;
                default:
                    System.out.println("指令无效，请重新输入！");
                    break;
            }
            choice = subMenu();
        }
    }

    //文件导入子菜单
    public static int subMenu(){
        int comm = 1;
        Scanner sc = new Scanner(System.in);
        System.out.println("1.CSV文件导入");
        System.out.println("2.XLS文件导入");
        System.out.println("3.JSON文件导入");
        System.out.println("4.退出");
        System.out.print("请选择(1-4): ");
        comm = sc.nextInt();
        sc.nextLine(); // 消耗换行符
        return comm;
    }
}
